package com.demo.generator.controller;


import com.demo.generator.entity.GenTable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import result.Result;
import com.demo.generator.service.GenTableService;
import util.text.Convert;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 代码生成 操作处理
 *
 * @author fbl
 */
@RestController
@RequestMapping("/generator")
@Api(value = "GenController" , tags = "自动生成代码管理")
public class GenController {
    @Autowired
    private GenTableService genTableService;

    /**
     * 导入表结构
     */
    @PostMapping("/importDownloadTable")
    @ApiOperation(value = "导入表结构")
    public Result importTableSave(HttpServletResponse response, @RequestParam("tableName") String tableName) {
        String[] tableNames = Convert.toStrArray(tableName);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return Result.success();
    }


    @PostMapping("/download/table")
    @ApiOperation(value = "批量生成代码(下载方式)")
    public Result DownloadTableSave(HttpServletResponse response, @RequestParam("tableName") String tableName) throws IOException {
        String[] tableNames = Convert.toStrArray(tableName);
        // 批量生成代码
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
        return Result.success();
    }

    @PostMapping("/myPath/table")
    @ApiOperation(value = "自定义路径生成代码")
    public Result myPathTableSave(@RequestParam("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return Result.success();
    }


    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin" , "*");
        response.addHeader("Access-Control-Expose-Headers" , "Content-Disposition");
        response.setHeader("Content-Disposition" , "attachment; filename=\"demo.zip\"");
        response.addHeader("Content-Length" , "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
